/**
 * @Author: 490912587@qq.com
 * @Description:
 * @File:  Index.go
 * @Version: 1.0.0
 * @Date: 2021/12/10 10:48
 */

package fileos_local

import (
	"errors"
	"fmt"
	"github.com/shopspring/decimal"
	"github.com/spf13/afero"
	"io/ioutil"
	"os"
	"server/tool"
	"strconv"
	"time"
)

type Files struct {
	FileName   string    `gorm:"comment:'文件名称'";json:"file_name"`
	FilePath   string    `gorm:"comment:'文件路径'";json:"file_path"`
	Path       string    `gorm:"comment:'文件完整路径'";json:"path"`
	FileSuffix string    `gorm:"comment:'文件后缀'";json:"file_suffix"`
	FileSize   string    `gorm:"comment:'文件尺寸'";json:"file_size"`
	OpTime     time.Time `gorm:"comment:'操作日期'";json:"op_time"`
}

var fileInfo Files

func WriteFile(path string, suffix string, file []byte) (Files, error) {
	rootPath, _ := os.Getwd()
	appFS := afero.NewOsFs()
	timeUtc := strconv.FormatInt(time.Now().Unix(), 10)
	t := time.Now()
	timeYMD := strconv.FormatInt(int64(t.Year()), 10) + strconv.FormatInt(int64(t.Month()), 10) + strconv.FormatInt(int64(t.Day()), 10)
	fileName := rootPath + "/public/" + path + timeYMD + "/" + tool.Md5(timeUtc) + "." + suffix
	err1 := appFS.Mkdir(rootPath+"/public/"+path+timeYMD+"/", 0644)
	err2 := afero.WriteFile(appFS, fileName, file, 0644)
	info, err := appFS.Stat(fileName)
	if os.IsNotExist(err) && err1 != nil && err2 != nil {
		fmt.Print("失败可能出现的原因：" + err.Error() + "/" + err1.Error() + "/" + err2.Error())
		return fileInfo, err
	} else {
		size, _ := decimal.NewFromFloat(float64(info.Size()) / float64(1024)).Round(3).Float64()
		fileInfo = Files{
			FileName:   tool.Md5(timeUtc) + "." + suffix,
			FilePath:   path + timeYMD + "/",
			Path:       path + timeYMD + "/" + tool.Md5(timeUtc) + "." + suffix,
			FileSuffix: suffix,
			FileSize:   strconv.FormatFloat(size, 'f', 3, 64) + "KB",
			OpTime:     info.ModTime(),
		}
		return fileInfo, nil
	}
}
func DelFile(filePath string, fileName string) error {
	rootPath, _ := os.Getwd()
	appFS := afero.NewOsFs()
	//先删除文件，再删除目录
	err := appFS.Remove(rootPath + "/public/" + filePath + fileName)
	_, err1 := appFS.Stat(rootPath + "/public/" + filePath + fileName)
	//判断文件目录是否还有其它文件，没有的话需要删除目录
	dir, _ := ioutil.ReadDir(rootPath + "/public/" + filePath)
	if len(dir) == 0 {
		_ = appFS.RemoveAll(rootPath + "/public/" + filePath)
	} else {
		fmt.Print("文件夹不为空！\r\n")
	}
	if os.IsNotExist(err1) && err == nil {
		return nil
	} else {
		fmt.Print("文件不存在，删除失败！\r\n")
		return errors.New("文件不存在！")
	}
}
